package com.gjintel.framework.menu.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.cache.InitCacheData.CacheType;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;
import com.gjintel.framework.menu.model.Model;
import com.gjintel.framework.menu.service.IMenuService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.dto.TreeDto;
import com.gjintel.sdk.util.StringUtil;

@RequestMapping("/framework/menu")
@Controller
public class MenuController {
	private static final Logger LOG = Logger.getLogger(MenuController.class);
	@Autowired
	private IMenuService menuService;

	/**
	 * @description 根据ID对当前的操作进行控制（ID为空，代表当前是添加操作，ID不为空，代表当前是更新操作）
	 * @author fengya
	 * @date 2015-7-30 上午10:54:34
	 * @param id
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/input")
	public ModelAndView input(String id) {
		ModelAndView mv = new ModelAndView("framework/menu/menu-input");
		Model model = null;
		if (!StringUtil.isEmpty(id)) {
			model = (Model) InitCacheData.getInstance().getCacheData(CacheType.MENU).get(id);
			if (!StringUtil.isEmpty(model.getPid())) {
				Object obj = InitCacheData.getInstance().getCacheData(CacheType.MENU).get(model.getPid());
				if (obj != null) {
					Model pModel = (Model) obj;
					model.setpName(pModel == null ? "" : pModel.getName());
				}
			}
			mv.addObject("menu", model);
		}
		return mv;
	}

	/**
	 * @方法名：getModelTree
	 * @功能说明：得到机构树
	 * @author fengya
	 * @date 2014-4-26 下午04:07:36
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getModelTreeDialog")
	@ResponseBody
	public JSONObject getModelTreeDialog(String id, String nodeName, String deleteIds) {
		// 树中节点所在的集合
		List<TreeDto> treeList = new ArrayList<TreeDto>();
		try {
			if (nodeName != null) {
				nodeName = URLDecoder.decode(nodeName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			LOG.debug("汉字转换错误！", e);
		}
		Map jsonData = new HashMap();
		// 查询到的节点ID的集合
		List<String> selIds = this.menuService.getModelTree(treeList, id, nodeName, deleteIds, true);
		jsonData.put("selIds", JSONArray.fromObject(selIds));
		jsonData.put("tree", JSONArray.fromObject(treeList));
		return JSONObject.fromObject(jsonData);
	}

	@RequestMapping("/getModelTree")
	@ResponseBody
	public JSONArray getModelTree(String id) {
		// 树中节点所在的集合
		List<TreeDto> treeList = new ArrayList<TreeDto>();
		this.menuService.getModelTree(treeList, id, null, null, false);
		return JSONArray.fromObject(treeList);
	}

	/**
	 * @description 分页排序查询数据
	 * @author fengya
	 * @date 2015-7-30 上午11:10:47
	 * @param page
	 * @param menu
	 * @param sort
	 * @return
	 * @return JSONObject
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/list")
	@ResponseBody
	public JSONObject list(Page page, Model menu, Sort sort) {
		this.menuService.findAll(page, menu, sort);
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 保存、更新数据
	 * @author fengya
	 * @date 2015-7-30 上午11:10:38
	 * @return void
	 * @throws Exception
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpSession session, Model menu) {
		User user = (User) session.getAttribute("loginUser");
		if (menu != null) {
			boolean sign = false;
			if (StringUtil.isEmpty(menu.getId())) {
				menu.setId(null);
				menu.setCreateTime(new Date());
				menu.setCreaterId(user.getId());
				menu.setCreaterName(user.getName());
				sign = true;
			}
			if (menu.getDisSort() == null) {
				menu.setDisSort(0);
			}
			menu.setUpdateTime(new Date());
			menu.setUpdaterName(user.getName());
			menu.setUpdaterId(user.getId());
			this.menuService.saveOrUpdate(menu);
			InitCacheData.getInstance().initModelData();
			if (sign) {
				LogUtil.addLog(new LogInfo("添加菜单", user.getId(), user.getName(), String.valueOf(LogType.ADD.ordinal()), menu.getClass().getSimpleName(), menu.getId()));
			} else {
				LogUtil.addLog(new LogInfo("更新菜单", user.getId(), user.getName(), String.valueOf(LogType.UPDATE.ordinal()), menu.getClass().getSimpleName(), menu.getId()));
			}
			return Constant.SAVE_SUCCESS;
		}
		return Constant.SAVE_UN_SUCCESS;
	}

	/**
	 * @description 根据选择的模块ID进行删除操作
	 * @author fengya
	 * @date 2015-7-30 上午11:16:38
	 * @param deleteIds
	 * @return
	 * @throws Exception
	 * @return String
	 */
	@RequestMapping("/remove")
	@ResponseBody
	public String remove(HttpSession session, String deleteIds) {
		User user = (User) session.getAttribute("loginUser");
		this.menuService.removeData(deleteIds);
		InitCacheData.getInstance().initModelData();
		LogUtil.addLog(new LogInfo("删除菜单", user.getId(), user.getName(), String.valueOf(LogType.DELETE.ordinal()), Model.class.getSimpleName(), deleteIds));
		return Constant.DEL_SUCCESS;
	}
}
